package com.sdu.cloudservice.action;

import com.auth0.jwt.JWT;
import com.sdu.cloudservice.dto.Envelope;
import com.sdu.cloudservice.service.ActualPriceService;
import com.sdu.cloudservice.token.UserToken;
import com.sdu.cloudservice.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**价格相关的接口
 * Create by zekdot on 19-6-28.
 */
@Controller
@CrossOrigin
@RequestMapping("/price")
public class PriceAction {
    @Autowired
    private ActualPriceService actualPriceService;

    @RequestMapping("/query")
    @ResponseBody
    @UserToken
    public String queryRealPrice(HttpServletRequest httpServletRequest, String zoneId, String instanceId, String startTime, String endTime){
        try{
            // 从 http 请求头中取出 token
            String token = httpServletRequest.getHeader("token");
            String username;
            // 如果是管理员
            if(PasswordUtil.getRole(token).equals("admin")){
                // 直接设置用户名为管理员
                username = "admin";
            }else{
                // 从token还原用户名
                username = JWT.decode(token).getAudience().get(0);
            }
//            String username = "admin";
            return actualPriceService.getActualPrice(username,zoneId,instanceId,startTime,endTime).toString();
        }catch (Exception e){
            e.printStackTrace();
            return Envelope.systemError.toString();
        }
    }
}
